const jwt = require('jsonwebtoken');
const config = require('../config/config');
const User = require('../models/user');


/**
 * 登录 
 */
const login = async ctx => {
    const params = ctx.request.body;
    const payload = {
        username: params.username,
    }
    const token = jwt.sign(payload, config.auth.admin_secret, {expiresIn: '1h'});
    /**
     * 
     * token 返回数据格式，exp：token过期时间，iat：token产生时间
     {
        exp: 1533727434,
        iat: 1533641034,
        username: "koa"
     }
     */

    ctx.cookies.set('Token-Auth', token);
    ctx.sendSucc(token, '登陆成功');
}

/**
 * 创建用户
 */
const createUser = async ctx => {
    const cp = ctx.request.body;
    const rp = {...cp};
    try {
        let user = await User.findOne({username: cp.username});
        if (user) {
            ctx.sendError({}, '该用户名已存在');
        } else {
            let userData = await User.create(rp);
            ctx.sendSucc(userData);
        }
    } catch (err) {
        ctx.sendError(err);
    }

}

/**
 * 获取用户列表
 */
const findUserList = async ctx => {
    try {
        let userList = await User.find({});
        ctx.sendSucc(userList);

    } catch (err) {
        ctx.sendError(err);
    }
}

/**
 * 删除某个用户
 */
const deleteUser = async ctx => {
    const cp = ctx.request.body;
    try {
        const result = await User.findByIdAndRemove({_id: cp._id});
        ctx.sendSucc(result);
    } catch(err) {
        ctx.sendError(err);
    }
}

/**
 * 获取用户信息
 */
const getInfo = async ctx => {
    const info = ctx.jwtinfo;
    ctx.sendSucc(info);
}


module.exports = {
    login,
    createUser,
    findUserList,
    deleteUser,
    getInfo
}